package cn.topevery.garden.dal.dao.impl;

import cn.topevery.garden.dal.dao.EvaluationFileDao;
import cn.topevery.garden.dal.dao.EvaluationLogDao;
import cn.topevery.garden.entity.po.EvaluationLog;
import cn.topevery.garden.entity.query.EvaluationLogQuery;
import cn.topevery.garden.entity.query.EvaluationRulesQuery;
import cn.topevery.garden.entity.vo.EvaluationLogVO;
import cn.topevery.garden.framework.base.BaseDaoImpl;
import hw.topevery.basis.entity.po.SysUser;
import hw.topevery.basis.runtime.UserRuntime;
import hw.topevery.framework.db.CommandType;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.db.entity.SqlQueryMate;
import hw.topevery.framework.db.enums.ScriptConditionEnum;
import hw.topevery.framework.entity.DbCsp;
import hw.topevery.framework.entity.KeyValue;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 检查考评上报记录表
 *
 * @author code-generate
 * @date 2022-01-05
 */
@Repository
public class EvaluationLogDaoImpl extends BaseDaoImpl<EvaluationLog> implements EvaluationLogDao {
    @Autowired
    private EvaluationFileDao evaluationFileDao;
    @Override
    public <P extends DbCsp> List<EvaluationLog> getSearch(P para) {
        return null;
    }

    

    @Override
    public DataPager<EvaluationLogVO> listPage(EvaluationLogQuery query) {
        String table = "t_evaluation_log tel";

        String columns = "tel.*";

        int pageIndex = query.pageIndex - 1;
        int pageSize = query.pageSize;

        SqlQueryMate sqlQueryMate = new SqlQueryMate(table).setColumns(columns).setOrderBy("tel.c_id desc");
        sqlQueryMate
                .where(true, "tel.c_db_status", ScriptConditionEnum.Eq, 0)
        ;

        return getDataPager(sqlQueryMate, pageSize, pageIndex, EvaluationLogVO.class);
    }

    @Override
    public EvaluationLog getEntityByColumn(String key,String value){
        KeyValue<String> map=new KeyValue<>();
        map.key=key;
        map.value=value;
        return getEntityByColumnEqValue(map);
    }

    @Override
    public void commit(EvaluationLog log, Integer userId) {
        SysUser user = UserRuntime.getSysUser();
        log.setDbUpdateDate(LocalDateTime.now());
        log.setDbUpdateId(userId);
        log.setUserId(userId);
        if (log.getClassScore() - log.getCounts() * log.getRuleScore() > 0 || log.getClassScore() == 0) {
            log.setDockScore(log.getCounts() * log.getRuleScore());
        } else {
            log.setDockScore(log.getClassScore());
        }
        if (log.getId() != null) {//修改
            evaluationFileDao.deleteByLogId(log.getId(), userId);
            update(user.userId, log);
        } else {
            log.setCreateId(user.userId);
            log.setCreateTime(LocalDateTime.now());
            log.setDbStatus(false);
            insert(user.userId, log);
        }
        if (log.getFileList() != null && !log.getFileList().isEmpty()) {
            evaluationFileDao.saveFiles(log.getFileList().stream().peek(temp -> {
                temp.setCreateTime(LocalDateTime.now());
                temp.setCreateId(user.userId);
                temp.setLogId(log.getId());
                temp.setDbStatus(false);
                temp.setDbUpdateDate(LocalDateTime.now());
                temp.setDbUpdateId(userId);
            }).collect(Collectors.toList()));
        }
    }

    @Override
    public List<EvaluationLog> getReportList(EvaluationRulesQuery query) {
        StringBuffer sb = new StringBuffer();
        sb.append("select * from t_evaluation_log where c_db_status = 0");

        if (StringUtils.isNotBlank(query.getRuleId())) {
            sb.append(" and c_rule_id = ' "+ query.getRuleId()+"'");
        }
        if (StringUtils.isNotBlank(query.getDeptId())) {
            sb.append(" and c_dept_id = ' "+ query.getDeptId()+"'");
        }
        if (StringUtils.isNotBlank(query.getBeginDate())) {
            sb.append(" and c_log_date BETWEEN  "+ query.getBeginDate()+" and " + query.getEndDate());
        }
        AtomicReference<List<EvaluationLog>> vo = new AtomicReference<>(new ArrayList<>());
        run(sb.toString(), CommandType.Text, dbCommand -> {
            vo.set(dbCommand.executeToList(EvaluationLog.class));
        });

        return vo.get();
    }

    @Override
    public void deleteById(Integer id, Integer userId) {

        String sql = "update t_evaluation_log set c_db_status = 1  where c_id = " + id;
        run(sql, CommandType.Text, dbCommand -> {
            dbCommand.executeNonQuery();
        });
    }

    @Override
    public List<Map<String, Object>> getAllLogForMap() {
        return getMap("select\n" +
                "        c_id,\n" +
                "        IFNULL(c_lng,0) c_lng,\n" +
                "        IFNULL(c_lat,0) c_lat\n" +
                "        from t_evaluation_log where c_db_status = 0 and c_lng is not null");
    }
}
